package com.guochenglang.www.service.impl;

import com.guochenglang.www.service.EmailService;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;

/**
 * 发邮箱验证码
 *
 * @author 郭程朗
 */
public class EmailServiceImpl implements EmailService {
    public EmailServiceImpl() {
    }

    /**
     * 发送邮箱验证码
     *
     * @param to       发送到的邮箱
     * @param subject  发送的邮箱
     * @param code     身份码
     * @param identify 验证码
     */
    @Override
    public void sendEmail(String to, String subject, String code, String identify) {
        //邮箱服务器
        String host = "smtp.qq.com";
        Properties props = System.getProperties();
        props.setProperty("mail.smtp.host", host);
        props.put("mail.smtp.auth", "true");
        Session session = Session.getDefaultInstance(props, new Authenticator() {
            @Override
            public PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(subject, code);
            }
        });
        MimeMessage message = new MimeMessage(session);
        try {
            //头部字段
            //发送邮箱验证吗
            message.setFrom(new InternetAddress(subject));
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
            message.setSubject("验证码", "UTF-8");
            message.setText("你的验证码为" + identify, "UTF-8");
            Transport.send(message);
        } catch (MessagingException e) {
            throw new RuntimeException(e);
        }


    }

}
